package club.yunqiang.rabbitmqapi.confirmlistener;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConfirmListener;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author 张云强
 * @date 2019/12/7
 */
public class Producer {

    public static void main(String[] args) throws IOException, TimeoutException {
        // 1、创建ConnectionFactory
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("localhost");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");

        // 2、获取 Connection
        Connection connection = connectionFactory.newConnection();

        // 3、通过 Connection 获取 Channel
        Channel channel = connection.createChannel();

        // 4、指定消息的确认模式
        channel.confirmSelect();

        // 5、投递消息
        String exchangeName = "test_confirm_exchange";
        String routingKey = "confirm.save";
        String msg = "Hello RabbitMQ send confirm message!";
        channel.basicPublish(exchangeName, routingKey, null, msg.getBytes());

        // 6、添加确认监听
        channel.addConfirmListener(new ConfirmListener() {
            @Override
            public void handleAck(long deliveryTag, boolean multiple) throws IOException {
                System.out.println("----- ack! -----");
            }

            @Override
            public void handleNack(long deliveryTag, boolean multiple) throws IOException {
                System.out.println("----- no ack! -----");
            }
        });
    }

}
